$(function () {
    var $datagrid = $("#datagrid"), $toolbar = $("#toolbar"), $charteredType = $("#charteredType"), $title = $("#title"),
        $dialog = $("#dialog");
    $("#editChartered").on("click", function () {
        var rows = $datagrid.datagrid('getSelected');
        if(rows){
            var targetId=rows.Id ;
            openDialog("form-edit.jsp?targetId="+targetId);
        }else{
            Constant.showMessage("请选择目标");
        }
    });
    $("#saveChartered").on("click",function(){
        openDialog();
    });
    $charteredType.combobox({
        onChange: function (v, o) {
            doSearch();
        }
    });
    function saveAccount() {
        $("form").form("submit", {
            url: $("form").attr("action"),
            onSubmit: function () {
                var isValid = $(this).form('validate');
                if (!isValid) {
                    $.messager.progress('close');	// hide progress bar while the form is invalid
                }
                return isValid;
            },
            success: function (respText) {
                var  resp= $.parseJSON(respText);
                Constant.showMessage(resp.AlertMessage,resp.message, "操作完成");
                console.info(resp);
                if (resp.ReturnCode == 1) {
                    uploading(resp.DataList);
                    uploadings(resp.DataList);
                    $("#datagrid").datagrid("reload");
                    $dialog.dialog("close");
                }
            }
        });
    }
    function updateAccount() {
        $("form").form("submit", {
            url: $("form").attr("action"),
            onSubmit: function () {
                var isValid = $(this).form('validate');
                if (!isValid) {
                    $.messager.progress('close');	// hide progress bar while the form is invalid
                }
                return isValid;
            },
            success: function (respText) {
                var  resp= $.parseJSON(respText);
                Constant.showMessage(resp.AlertMessage,resp.message, "操作完成");
                console.info(resp);
                if (resp.ReturnCode == 1) {
                    uploading2(resp.DataList);
                    uploadings2(resp.DataList);
                    $("#datagrid").datagrid("reload");
                    $dialog.dialog("close");
                }
            }
        });
    }

    function uploading(ticketId){
        var files = document.getElementById('logoImage').files;
        for (var i = 0; i < files.length; i++) {
            var fd = new FormData();
            fd.append('fileToUpload', files[i]);
            var xhr = new XMLHttpRequest();
            xhr.upload.addEventListener('progress', function () {
            }, false);
            xhr.addEventListener('load', function () {
            }, false);
            xhr.addEventListener('error', function () {
            }, false);
            xhr.addEventListener('abort', function () {
            }, false);
            xhr.open('POST', Constant.ctx('/mulanweb/admin/photo/save?targetId='+ticketId+'&typeId=16'));//typeId=13表示为门票券票图片
            xhr.send(fd);
        }
    }
    function uploadings(ticketId){
        var files = document.getElementById('fileImage').files;
        for (var i = 0; i < files.length; i++) {
            var fd = new FormData();
            fd.append('fileToUpload', files[i]);
            var xhr = new XMLHttpRequest();
            xhr.upload.addEventListener('progress', function () {
            }, false);
            xhr.addEventListener('load', function () {
            }, false);
            xhr.addEventListener('error', function () {
            }, false);
            xhr.addEventListener('abort', function () {
            }, false);
            xhr.open('POST', Constant.ctx('/mulanweb/admin/photo/save?targetId='+ticketId+'&typeId=15'));//typeId=13表示为门票券票图片
            xhr.send(fd);
        }
    }

    function uploading2(ticketId){
        var files = document.getElementById('detail-logoImage').files;
        for (var i = 0; i < files.length; i++) {
            var fd = new FormData();
            fd.append('fileToUpload', files[i]);
            var xhr = new XMLHttpRequest();
            xhr.upload.addEventListener('progress', function () {
            }, false);
            xhr.addEventListener('load', function () {
            }, false);
            xhr.addEventListener('error', function () {
            }, false);
            xhr.addEventListener('abort', function () {
            }, false);
            xhr.open('POST', Constant.ctx('/mulanweb/admin/photo/update?targetId='+ticketId+'&typeId=16'));//typeId=13表示为门票券票图片
            xhr.send(fd);
        }
    }
    function uploadings2(ticketId){
        var files = document.getElementById('detail-fileImage').files;
        for (var i = 0; i < files.length; i++) {
            var fd = new FormData();
            fd.append('fileToUpload', files[i]);
            var xhr = new XMLHttpRequest();
            xhr.upload.addEventListener('progress', function () {
            }, false);
            xhr.addEventListener('load', function () {
            }, false);
            xhr.addEventListener('error', function () {
            }, false);
            xhr.addEventListener('abort', function () {
            }, false);
            xhr.open('POST', Constant.ctx('/mulanweb/admin/photo/update?targetId='+ticketId+'&typeId=15'));//typeId=13表示为门票券票图片
            xhr.send(fd);
        }
    }
    function openDialog(editPath) {
        $dialog.dialog({
            title: editPath?"编辑内容":"新增内容",
            width: 500,
            height: 500,
            closed: false,
            cache: false,
            href:editPath || 'form.jsp',
            modal: true,
            onClose: function () {
                $("#form-dialog").dialog("destroy");
                $("#logoImage").val("");
                $("#fileImage").val("");
                $(".upload_delete").click();
                $("#preview").html("");
            },
            buttons: [{
                text: '保存',
                handler: editPath?updateAccount:saveAccount
            }]
        });
    }
    $datagrid.datagrid({
        singleSelect: true,
        fit: true,
        border: false,
        fitColumns: true,
        url: Constant.ctx("/mulanweb/admin/chartered/search"),
        method: 'post',
        pagination: true,
        toolbar: $toolbar,
        columns: [[
            {field: 'Id', title: '编号'},
            {field: 'Title', title: '标题'},
            {field: 'Price', title: '单价'},
            {field:'CreateTime',title:'下单时间'},
            {field: 'HotCommodity', title: '操作', formatter: function (v, r, i) {
                var html = '';
                if (v == 0) {
                   html = html+ '<a href="#" onclick="saveHot('+r.Id+')">设置爆款</a>';
                } else if (v == 1) {
                    html = html+'<a href="#" onclick="saveHot('+r.Id+')">取消爆款</a>';
                }
                if(!r.DeleteTime){
                    html = html+ '  <a href="#" onclick="deleteContent('+r.Id+',24)">删除</a>'
                }
                return html;
            }}
        ]],
       onBeforeLoad: function (param) {
            param.PageNumber = param.page;
            param.PageSize = param.rows;
           var title = $("#title").val();
           if(title){
               param.title = title ;
           }
           var typeId = $("#charteredType").combo("getValue");
           if(typeId && typeId != 0 ){
               param.typeId = typeId;
           }
            return true;
        },
       loadFilter: function (data) {
            var newData = {};
            if (data.ReturnCode == 1) {
                newData.rows = data.DataList;
                if (newData.rows.length > 0) {
                    newData.total = data.TotalRow;
                } else {
                    newData.total = 0;
                }
            }
            return newData;
        },
        onDblClickRow: function (index, rows) {
            showDetail(rows);
        }
    });
    function showDetail(row) {
        $.post(Constant.ctx("/mulanweb/admin/chartered/getDetail"),{targetId:row.Id},function(info){
            var module = $("#detail").html();
            var compileModule = Template7.compile(module);
            var resultModule = compileModule(info.target);
            $("#dialogDetail").html(resultModule);
        })
        $("#dialogDetail").dialog({
            title:'详情',
            width:400,
            height:500,
        });
    }
})
function doSearch() {
    $("#datagrid").datagrid("reload");
}